package com.xinchen.aiowaste.ui.fragment

import android.content.Context
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.AppUtils
import com.gprinter.bean.PrinterDevices
import com.gprinter.utils.CallbackListener
import com.gprinter.utils.ConnMethod
import com.kongqw.network.monitor.enums.NetworkState
import com.maple.common.jiabo.Printer
import com.maple.common.jiabo.Utils
import com.maple.common.ui.adapter.DeviceAdapter
import com.maple.common.usbManger.UsbDeviceManager
import com.maple.common.widget.dialog.DeviceDialog
import com.maple.common.widget.spinner.UnitSpinnerAdapter
import com.maple.model.data.AccountType
import com.maple.model.data.UsbDevice
import com.maple.model.enum.PrintEnum
import com.maple.utils.ext.afterTextChanged
import com.maple.utils.ext.toGone
import com.maple.utils.ext.toVisible
import com.maple.utils.store.AioDBHelper
import com.maple.utils.util.LogUtils
import com.maple.utils.util.UIUtils
import com.xinchen.aiowaste.R
import com.xinchen.aiowaste.base.BaseFragment
import com.xinchen.aiowaste.ui.activity.HomeActivity
import com.xinchen.aiowaste.vm.AccountViewModel
import kotlinx.coroutines.MainScope
import android.hardware.usb.UsbDevice as UDevice


class LoginFragment : BaseFragment() {

    private var ivLogo:ImageView? = null
    private var etAccount: EditText? = null
    private var etPassword: EditText? = null
    private var ibtnAccountClear: ImageButton? = null
    private var ibtnPasswordEye: ImageButton? = null
    private var btnLogin: Button? = null

    private var cbRememberPwd: CheckBox? = null


    private var spUnit: AppCompatSpinner? = null

    private var llLogin: LinearLayout? = null

    private var tvDeviceStatus: TextView? = null
    private var tvVersionName: TextView? = null

    private var tvNetworkState: TextView? = null


    private val unitAdapter: UnitSpinnerAdapter by lazy {
        UnitSpinnerAdapter(requireContext(), com.maple.res.R.color.primary).apply {
            this.setData(listOf("产废企业"))
        }
    }

    private val eyeShowDrawable by lazy {
        UIUtils.getDrawable(R.drawable.ic_eye_show)
    }
    private val eyeHideDrawable by lazy {
        UIUtils.getDrawable(R.drawable.ic_eye_hide)
    }

    private val viewModel by viewModels<AccountViewModel>()

    override fun hasNavController(): Boolean  = true

    override fun hasNetworkState(): Boolean = true

    override fun getLayoutId(): Int = R.layout.fragment_login

    override fun initView(view: View, savedInstanceState: Bundle?) {
        super.initView(view, savedInstanceState)
        ivLogo = view.findViewById(R.id.iv_logo)
        ivLogo?.setOnClickListener {
            onOpenServer()
        }
        tvVersionName = view.findViewById(R.id.tv_version_name)
        tvVersionName?.text = "版本 ${AppUtils.getAppVersionName()}"
        tvDeviceStatus = view.findViewById(R.id.tv_device_status)
        tvNetworkState = view.findViewById(R.id.tv_network_state)
        tvNetworkState?.toVisible()

        cbRememberPwd = view.findViewById(R.id.cb_remember_pwd)
        if(AioDBHelper.getRememberPwd()) {
            cbRememberPwd?.isChecked = true
        }
        cbRememberPwd?.setOnCheckedChangeListener { compoundButton, b ->
            AioDBHelper.saveRememberPwd(b)
        }

        etAccount = view.findViewById(R.id.et_account)
        etAccount?.setText(AioDBHelper.getAccount())
        etPassword = view.findViewById(R.id.et_password)
        etPassword?.setText(AioDBHelper.getPassword())
        ibtnAccountClear = view.findViewById(R.id.ibtn_account_clear)
        ibtnPasswordEye = view.findViewById(R.id.ibtn_password_eye)
        spUnit = view.findViewById(R.id.sp_unit)
        spUnit?.adapter = unitAdapter
        val platform: Int = AioDBHelper.getPlatform()
        spUnit?.setSelection(unitAdapter.getPositionByName(getPlatformName(platform)),true)
        LogUtils.logGGQ("===platform====>>${getPlatformName(platform)}")

        llLogin = view.findViewById(R.id.ll_login)
        btnLogin = view.findViewById(R.id.btn_login)
        etAccount?.afterTextChanged {
            if(!TextUtils.isEmpty(it)) {
                ibtnAccountClear?.toVisible()
            } else {
                ibtnAccountClear?.toGone()
            }
        }

        etPassword?.afterTextChanged {
            if(!TextUtils.isEmpty(it)) {
                ibtnPasswordEye?.toVisible()
            } else {
                ibtnPasswordEye?.toGone()
            }
        }

        btnLogin?.setOnClickListener {
            onLogin()
        }
        ibtnAccountClear?.setOnClickListener {
            etAccount?.setText("")
        }
        ibtnPasswordEye?.setOnClickListener {
            if(etPassword == null) return@setOnClickListener
            UIUtils.editTransformation(etPassword!!,it as ImageView,eyeShowDrawable,eyeHideDrawable)
        }

    }

    private fun onLogin() {
        val account = etAccount?.text.toString().trim()
        val password = etPassword?.text.toString().trim()
        if(TextUtils.isEmpty(account)) {
            showToast("请输入用户名")
            return
        }
        if(TextUtils.isEmpty(password)) {
            showToast("请输入密码")
            return
        }
        val unit = spUnit?.selectedItem.toString()
        if(TextUtils.equals(AccountType.HINT.typeName,unit)) {
            showToast(unit)
            return
        }

        val platform = getPlatform(unit)
        viewModel.onLogin(account,password,cbRememberPwd?.isChecked?:false,platform)

    }


    private val deviceAdapter: DeviceAdapter by lazy {
        DeviceAdapter(requireContext()).apply {
            this.setData(arrayListOf())
            this.setListener(object :DeviceAdapter.OnClickListener{
                override fun onItemClick(pos: Int, item: UsbDevice?) {
                    item?.let {
                        if(it.printType == PrintEnum.NONE) {
                            // 重新获取设备
                            getUsbDevice()
                        } else {
                            connectPrint(it)
                        }
                    }
                }
            })
        }
    }

    private fun connectPrint(device: UsbDevice) {
        val usbDevice : UDevice? = Utils.getUsbDeviceFromName(requireContext(),device.name)
        usbDevice?.let {
            if(device.printType == PrintEnum.JIABO10) {
                val usb: PrinterDevices = PrinterDevices.Build()
                    .setContext(requireContext())
                    .setConnMethod(ConnMethod.USB)
                    .setUsbDevice(usbDevice)
                    .setCommand(com.gprinter.utils.Command.TSC)
                    .setCallbackListener(object : CallbackListener{
                        override fun onConnecting() {
                            setDeviceStatus("设备连接中")
                        }

                        override fun onCheckCommand() {
                            setDeviceStatus("设备查询指令中")
                        }

                        override fun onSuccess(printerDevices: PrinterDevices?) {
                            setDeviceStatus("设备已连接")
                            AioDBHelper.saveUsbDevice(device)
                        }

                        override fun onReceive(byteArray: ByteArray?) {
                            setDeviceStatus("设备读取数据")
                        }

                        override fun onFailure() {
                            setDeviceStatus("设备连接失败！")
                            MainScope().runCatching {
                                Printer.close()
                            }
                        }

                        override fun onDisconnect() {
                            setDeviceStatus("设备已断开")
                            MainScope().runCatching {
                                Printer.close()
                            }
                        }
                    })
                    .build()
                Printer.connect(usb)
            } else if(device.printType == PrintEnum.JINXCIN20) {

                if(UsbDeviceManager.getInstance().isConnect()) {
                    showToast("精芯打印机已连接");
                    return
                }
                if (UsbDeviceManager.getInstance().hasPermission(usbDevice)) {
                    val ret = UsbDeviceManager.getInstance().openDevice(usbDevice)
                    if (ret == 0) {
                        showToast("精芯打印机连接成功");
                    } else {
                        showToast("ret: ${ret}");
                    }
                } else {
                    UsbDeviceManager.getInstance().requestPermission(usbDevice)
                }
            } else {
                showToast("未知的打印机类型！")
            }
        }
    }

    private val deviceDialog: DeviceDialog by lazy {
        DeviceDialog(requireContext(),deviceAdapter)
    }

    override fun initData(savedInstanceState: Bundle?) {
        viewModel.defUI.showDialog.observe(this, Observer {
            showLoading()
        })

        viewModel.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })

        viewModel.defUI.toastEvent.observe(this, Observer {
            showToast(it)
        })
        viewModel.loginEvent.observe(this, Observer {
            onStartActivity(HomeActivity::class.java, isFinish = true)
        })

        etAccount?.setText("HBSCF0000000000001")
        etPassword?.setText("HBqwer1234.")
        val usbDevice: UsbDevice? = AioDBHelper.getUsbDevice()
        if(usbDevice == null || TextUtils.isEmpty(usbDevice.name)) {
            deviceDialogShow()
            getUsbDevice()
        } else {
            connectPrint(usbDevice)
        }

    }

    private val usbManager: UsbManager by lazy {
        requireActivity().getSystemService(Context.USB_SERVICE) as UsbManager
    }

    private fun getUsbDevice() {
        deviceAdapter.clear()
        val devices = usbManager.deviceList
        val deviceIterator = devices.values.iterator()
        val count = devices.size
        if (count > 0) {
            while (deviceIterator.hasNext()) {
                val device = deviceIterator.next()
                val deviceName = device.deviceName
                if (Utils.checkUsbDevicePidVid(device)) {
                    deviceAdapter.addDevice(UsbDevice(deviceName, PrintEnum.JIABO10))
                } else if(Utils.checkUsbDevicePidVid20(device)) {
                    deviceAdapter.addDevice(UsbDevice(deviceName, PrintEnum.JINXCIN20))
                }
            }
        } else {
            showToast("无USB设备")
            deviceAdapter.addDevice(UsbDevice("无USB设备"))
        }
    }



    private fun getPlatform(typeName: String): Int {
        return 4
    }

    private fun getPlatformName(platform: Int): String {
        return "处置企业"
    }

    private fun deviceDialogShow() {
        deviceDialog.show(requireActivity().supportFragmentManager,"bluetoothDialog")
    }
    private fun deviceDialogDismiss() {
        deviceDialog.dismiss()
    }
    private fun setDeviceStatus(status: String) {
        tvDeviceStatus?.text = "设备状态：${status}"
    }


    private fun onOpenServer() {
        navController?.navigate(R.id.action_loginFragment_to_serverFragment)
    }
}